package models

import (
	"bigdevops/src/common"
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strings"
)

// alertmanager实例 和机器的关系
// 1对多 机器只能属于1个alertmanager实例
// 新建alertmanager实例 就需要填入ip
// 主配置文件池
// D:\nyy_work\go_path\src\github.com\prometheus\alertmanager\config\config.go
type MonitorAlertmanagerPool struct {
	Model        // 不用每次写ID 和 createAt了
	Name  string `json:"name" validate:"required,min=1,max=50" gorm:"uniqueIndex;type:varchar(100);comment:alertmanager实例名称，支持使用通配符*进行模糊搜索" `

	// 选择多个采集器 实例 gossip 组集群
	AlertmanagerInstances StringArray `json:"alertmanagerInstances" `

	// D:\nyy_work\go_path\src\github.com\prometheus\prometheus\config\config.go
	// 下面是global段
	UserID         uint
	ResolveTimeout string `json:"resolveTimeout" gorm:"comment: 默认恢复时间"`
	GroupWait      string `json:"groupWait" gorm:"comment: 默认分组第一次等待时间"`
	GroupInterval  string `json:"groupInterval" gorm:"comment: 默认分组等待间隔"`
	RepeatInterval string `json:"repeatInterval" gorm:"comment: 默认重复发送时间"`

	GroupBy StringArray `json:"groupBy" gorm:"comment: 分组的标签"`
	// remoteWrite段
	Receiver string `json:"receiver" gorm:"comment: 兜底接收者"`

	// ExternalLabels \n join的结果
	GroupByFront   string `json:"groupByFront" gorm:"-"`
	Key            string `json:"key" gorm:"-"` //给前端表格
	CreateUserName string `json:"createUserName" gorm:"-"`
}

func (obj *MonitorAlertmanagerPool) Create() error {
	return Db.Create(obj).Error

}
func (obj *MonitorAlertmanagerPool) DeleteOne() error {

	return Db.Select(clause.Associations).Unscoped().Delete(obj).Error

}

func (obj *MonitorAlertmanagerPool) CreateOne() error {
	return Db.Create(obj).Error

}

func (obj *MonitorAlertmanagerPool) UpdateOne() error {
	return Db.Where("id = ?", obj.ID).Updates(obj).Error

}

// 要求新增和更新的时候 ip不能重复
func (obj *MonitorAlertmanagerPool) CheckIpExists() bool {
	all, err := GetMonitorAlertmanagerPoolAll()
	if err != nil {
		return true
	}
	ipMap := map[string]string{}
	for _, p := range all {
		p := p
		if p.Name == obj.Name {
			// 跳过自己
			continue
		}
		for _, ip := range p.AlertmanagerInstances {
			ipMap[ip] = ip
		}

	}

	for _, ip := range obj.AlertmanagerInstances {
		_, ok := ipMap[ip]
		if ok {
			return true
		}
	}
	return false
}

// 0值替换 前转后
func (obj *MonitorAlertmanagerPool) FillDefaultData() {
	if obj.ResolveTimeout == "" {
		obj.ResolveTimeout = "30m"
	}
	if obj.GroupWait == "" {
		obj.GroupWait = "10s"
	}
	if obj.GroupInterval == "" {
		obj.GroupInterval = "10s"
	}
	if obj.RepeatInterval == "" {
		obj.RepeatInterval = "1m"
	}

	obj.GroupBy = common.GenStringArrayByChangeLine(obj.GroupByFront)
	if len(obj.GroupBy) == 0 {
		obj.GroupBy = []string{"alertname"}
	}
}

// 后转前
func (obj *MonitorAlertmanagerPool) FillFrontAllData() {
	dbUser, _ := GetUserById(int(obj.UserID))
	if dbUser != nil {
		obj.CreateUserName = dbUser.Username
	}

	obj.GroupByFront = strings.Join(obj.GroupBy, "\n")

	//obj.ExternalLabelsFront = strings.Join(obj.ExternalLabels, "\n")
	obj.Key = fmt.Sprintf("%d", obj.ID)

}
func GetMonitorAlertmanagerPoolAll() (objs []*MonitorAlertmanagerPool, err error) {
	err = Db.Find(&objs).Error
	return
}

func GetMonitorAlertmanagerPoolCount() int {
	var count int64
	Db.Table("form_designs").Count(&count)
	return int(count)
}

func GetMonitorAlertmanagerPoolByLevel(level int) (objs []*MonitorAlertmanagerPool, err error) {
	err = Db.Where("level = ?", level).Preload("OpsAdmins").Find(&objs).Error
	return
}

// select * from ecs where
func GetMonitorAlertmanagerPoolByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*MonitorAlertmanagerPool, err error) {
	err = Db.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

func GetMonitorAlertmanagerPoolByInstanceId(instanceId string) (*MonitorAlertmanagerPool, error) {

	var dbObj MonitorAlertmanagerPool
	err := Db.Where("instance_id = ?", instanceId).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("MonitorAlertmanagerPool不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetMonitorAlertmanagerPoolById(id int) (*MonitorAlertmanagerPool, error) {

	var dbObj MonitorAlertmanagerPool
	err := Db.Where("id = ?", id).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("MonitorAlertmanagerPool不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}
